package com.fce.fcesystem.realm;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import com.fce.fcesystem.pojo.Permission;
import com.fce.fcesystem.pojo.User;
import com.fce.fcesystem.service.IUserService;

import java.util.List;

/**
 * @author zhangbingfan
 */
public class CustomerRealm extends AuthorizingRealm {

    @Autowired
    IUserService userService;

   @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String principal = (String) principalCollection.getPrimaryPrincipal();
        User user = userService.findRolesByAccount(principal);
        if (!CollectionUtils.isEmpty(user.getRoles())) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            user.getRoles().forEach(role ->{
                info.addRole(role.getName());
                //权限信息
                List<Permission> perms = userService.findPermsByRoleId(role.getId()).getPerms();
                System.out.println("perms========"+perms);
                if(!CollectionUtils.isEmpty(perms) && perms.get(0)!=null ){
                    perms.forEach(perm->{
                        info.addStringPermission(perm.getName());
                    });
                }
            });
            return info;
        }
        return null;
    }

   @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String principal =(String) authenticationToken.getPrincipal();
        User user = userService.selectUserByAccount(principal);
        if (!ObjectUtils.isEmpty(user)){
            return new SimpleAuthenticationInfo(user.getAccount(),user.getPassword(), ByteSource.Util.bytes(user.getSalt()),this.getName());
        }
        return null;
    }
}
